package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.Company;
import com.xuanzheng.company.entity.CompanyEmployee;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyEmployeeService;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.service.impl.CompanyEmployeeServiceImpl;
import com.xuanzheng.company.service.impl.CompanyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/reviewEmployeeApplication")
public class ReviewEmployeeApplicationServlet extends HttpServlet {
    private final CompanyEmployeeService companyEmployeeService = new CompanyEmployeeServiceImpl();
    private final CompanyService companyService = new CompanyServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取当前用户
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                out.write(gson.toJson(result));
                return;
            }
            
            // 检查用户是否是公司负责人
            if (user.getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有公司负责人可以审核入职申请");
                out.write(gson.toJson(result));
                return;
            }
            
            // 获取请求参数
            String applicationId = request.getParameter("applicationId");
            String statusStr = request.getParameter("status");
            String position = request.getParameter("position");
            String baseSalaryStr = request.getParameter("baseSalary");
            String rejectReason = request.getParameter("rejectReason");
            
            if (applicationId == null || applicationId.trim().isEmpty() || statusStr == null || statusStr.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "请求参数不完整");
                out.write(gson.toJson(result));
                return;
            }
            
            int status;
            try {
                status = Integer.parseInt(statusStr);
                if (status != 1 && status != 2) { // 只允许通过或拒绝
                    result.put("success", false);
                    result.put("message", "状态参数无效");
                    out.write(gson.toJson(result));
                    return;
                }
            } catch (NumberFormatException e) {
                result.put("success", false);
                result.put("message", "状态参数无效");
                out.write(gson.toJson(result));
                return;
            }
            
            // 如果是通过申请，检查职位和薪资参数
            BigDecimal baseSalary = null;
            if (status == 1) {
                if (position == null || position.trim().isEmpty()) {
                    result.put("success", false);
                    result.put("message", "职位不能为空");
                    out.write(gson.toJson(result));
                    return;
                }
                
                // 检查职位名称，不允许设置为"负责人"
                if (position.trim().equals("负责人")) {
                    result.put("success", false);
                    result.put("message", "不能将员工职位设置为负责人");
                    out.write(gson.toJson(result));
                    return;
                }
                
                if (baseSalaryStr == null || baseSalaryStr.trim().isEmpty()) {
                    result.put("success", false);
                    result.put("message", "基础薪资不能为空");
                    out.write(gson.toJson(result));
                    return;
                }
                
                try {
                    baseSalary = new BigDecimal(baseSalaryStr);
                    if (baseSalary.compareTo(BigDecimal.ZERO) < 0) {
                        result.put("success", false);
                        result.put("message", "基础薪资不能为负数");
                        out.write(gson.toJson(result));
                        return;
                    }
                } catch (NumberFormatException e) {
                    result.put("success", false);
                    result.put("message", "基础薪资格式无效");
                    out.write(gson.toJson(result));
                    return;
                }
            }
            
            // 获取申请详情
            CompanyEmployee application = companyEmployeeService.getApplicationById(applicationId);
            if (application == null) {
                result.put("success", false);
                result.put("message", "找不到指定的申请记录");
                out.write(gson.toJson(result));
                return;
            }
            
            // 获取公司信息
            Company company = companyService.getCompanyByManagerId(user.getId());
            if (company == null || !company.getId().equals(application.getCompanyId())) {
                result.put("success", false);
                result.put("message", "您无权审核此申请");
                out.write(gson.toJson(result));
                return;
            }
            
            // 设置默认拒绝原因
            if (status == 2 && (rejectReason == null || rejectReason.trim().isEmpty())) {
                rejectReason = "抱歉，您的入职申请未通过";
            }
            
            // 审核申请
            boolean success = companyEmployeeService.reviewApplication(applicationId, status, position, baseSalary, rejectReason);
            
            if (success) {
                result.put("success", true);
                result.put("message", status == 1 ? "已通过申请" : "已拒绝申请");
            } else {
                result.put("success", false);
                result.put("message", "审核失败，可能申请状态已变更");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "审核申请失败：" + e.getMessage());
        }
        
        out.write(gson.toJson(result));
        out.flush();
    }
} 